package com.ruoyi.iot.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.iot.domain.Agent;
import com.ruoyi.iot.domain.ExtraAgent;
import com.ruoyi.iot.service.IExtraAgentService;
import com.ruoyi.iot.service.IIotService;
import com.ruoyi.iot.vo.DistributorExtraVo;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName IotController
 * @Description 物联卡公共接口
 * @Author hly
 * @Date 2024/1/14 12:56
 */

@RestController
@RequestMapping(value = "/iot")
public class IotController extends BaseController {



    @Autowired
    private IIotService service;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IExtraAgentService extraAgentService;


    /**
     * @description: 获取物联卡系统 代理用户
     * @author: hly
     * @date: 2024/1/15 11:04
     * @return: com.ruoyi.common.core.domain.AjaxResult
     **/
    @PreAuthorize("@ss.hasRole('admin')")
    @RequestMapping(value = "/listAgent")
    public TableDataInfo listAgent(String name) {
        startPage();
        List<Agent> maps = service.listAgent(name);
        maps.forEach(x->{
            String iot_name = x.getName();
            SysUser sysUser = userService.selectUserByUserName(iot_name);
            x.setDisable(sysUser == null);
        });
        return getDataTable(maps);
    }

    /**
     * @description: 勾选物联卡代理 到系统用户中 并分配 iot 角色
     * @author: hly
     * @date: 2024/1/16 13:02
     * @param: ids
     * @return: com.ruoyi.common.core.domain.AjaxResult
     **/
    @PreAuthorize("@ss.hasRole('admin')")
    @RequestMapping(value = "/distributorAgents")
    public AjaxResult distributorAgents(@RequestBody List<Integer> ids) {
        if (ids.isEmpty()){
            return AjaxResult.error("参数为空");
        }
        List<Agent> agentList = service.getAgentListByIds(ids);
        for (Agent map : agentList) {
            SysUser user = new SysUser();
            Long[] roles = {3L};
            user.setUserName(map.getName());
            user.setNickName(map.getRealName()==null?map.getName():map.getRealName());
            user.setPassword(SecurityUtils.encryptPassword("123456"));
            user.setRemark("管理员划入到系统用户");
            user.setRoleIds(roles);
            userService.insertUser(user);
        }
        return AjaxResult.success();
    }

    @PreAuthorize("@ss.hasRole('admin')")
    @RequestMapping(value = "/distributorExtraAgents")
    public AjaxResult distributorExtraAgents(@RequestBody DistributorExtraVo extraVo) {
        System.out.println(extraVo);
        //删除所有额外店铺配置
        Integer id = extraVo.getId();
        extraAgentService.deleteExtraAgentByUserId(id.longValue());
        //新增数据
        List<Integer> ids = extraVo.getIds();
        if (!ids.isEmpty()) {
            List<Agent> agentList = service.getAgentListByIds(ids);
            agentList.forEach(x->{
                ExtraAgent extraAgent = new ExtraAgent();
                extraAgent.setSysUserId(id.longValue());
                extraAgent.setExtraAgentId(Long.parseLong(x.getId().toString()));
                extraAgent.setExtraAgentName(x.getName());
                extraAgentService.insertExtraAgent(extraAgent);
            });
        }
        return AjaxResult.success();
    }


    @RequestMapping(value = "/agentChilds")
    public AjaxResult agentChilds(@RequestParam(value = "userId") Long userId) {
        SysUser user = userService.selectUserById(userId);
        List<Agent> maps = service.agentChilds(user.getUserName());
        List<String> names = maps.stream().map(Agent::getName).collect(Collectors.toList());
        List<Agent> agents = service.findAgents(names);
        List<Object> result = new ArrayList<>();
        result.add(maps);
        result.add(agents);
        List<ExtraAgent> extraAgents = extraAgentService.selectExtraAgentByUserId(userId);
        result.add(extraAgents);
        return AjaxResult.success(result);
    }




}
